var express = require('express');
var router = express.Router();

const {userModel,branchModel} = require('../model/models')
/* GET users listing. */
router.get('/users', async(req, res) =>{
  // let id = req.user.id;
  // // 查找出当前登录的用户
  // let user = await userModel.findOne({_id:id})
  // // 如果是管理员则查找出所有用户
  // let data = [];
  // if(['管理员','超级管理员'].indexOf(user.user) != -1){
  //   data = await userModel.find().populate('b_id').lean().exec()
  //   for(i in data){
  //     if(!data[i].b_id){
  //       let branch = await branchModel.find({responsible:data[i]._id})
  //       data[i].b_id = branch
  //     }
  //   }
  // }else{
  //   // 判断当前用户是不是部门负责人
  //   if(user.b_id){
  //     // 查出当前部门的所有成员
  //     data = await userModel.find({b_id:user.b_id}).populate('b_id').lean().exec()
  //     // 查出当前部门的负责人信息
  //     let breach = await branchModel.findOne({_id:user.b_id}).populate('responsible')
  //     data.unshift(breach.responsible)
  //   }else{

  //   }
  // }
    let  data = await userModel.find().populate('b_id').lean().exec()
    for(i in data){
      if(!data[i].b_id){
        let branch = await branchModel.find({responsible:data[i]._id})
        data[i].b_id = branch
        data[i].responsible = branch.length >0 ? 1 : 0
      }
    }
  res.send({
    code:200,
    data
  })
});
// 修改员工信息
router.patch('/edituser/:id',async(req,res) =>{
  let body = req.body
  let id = req.params.id
  await userModel.updateOne({_id:id},{$set:body})
  const user = await userModel.findOne({_id:id}).populate('b_id').lean().exec()
  if(!user.b_id){
    const breach = await branchModel.find({responsible:user._id}).exec()
    user.b_id = breach
    data[i].responsible = breach.length >0 ? 1 : 0
  }
  res.send({
    code:200,
    msg:'修改成功',
    user

  })
})
module.exports = router;
